/**
 * Created by YJH on 2018/5/29.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    ListView,
    RefreshControl,
    DeviceEventEmitter,
} from 'react-native';
import DataRespository, {FLAG_STORAGE} from '../../expand/dao/DataRespository';
import RespositoryCell from '../../common/RespositoryCell';
import RepositoryDetailPage from './RepositoryDetailPage';
import ProjectModulePopular from '../../module/ProjectModulePopular';
import FavoriteDao from '../../expand/dao/FavoriteDao';
import FavoriteUtil from '../../util/FavoriteUtil'

const URL = 'https://api.github.com/search/repositories?q=';
const SEARCH_STR = '&sort=stars';
export default class TabPage extends Component {
    constructor(props) {
        super(props);
        this.dataRespository = new DataRespository(FLAG_STORAGE.flag_popular);
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular);
        this.items = [];
        this.state = ({
            searchTxt: this.props.tabLabel,
            result: '页面数据加载中..',
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2
            }),
            isLoading: false,
            favoriteKeys: [],
            theme: this.props.hTheme,
        })
    }

    getFavoriteKey() {
        return this.favoriteDao.getFavorKeys()
            .then(keys => {
                if (keys) {
                    this.updateState({favoriteKeys: keys})
                }
                this.flushFavoriteState()
            })
            .catch(e => {
                this.flushFavoriteState();
            })
    }

    genUrl(search_key) {
        return URL + search_key + SEARCH_STR;
    }

    /** 更新 project item 的搜藏的状态*/
    flushFavoriteState() {
        let projectModules = [];
        for (let i = 0, l = this.items.length; i < l; i++) {
            projectModules.push(new ProjectModulePopular(this.items[i],
                FavoriteUtil.checkFavorite(this.items[i], this.state.favoriteKeys)))
        }

        this.updateState({
            result: JSON.stringify(projectModules),
            isLoading: false,
            dataSource: this.getDataSource(projectModules),
        });
    }

    getDataSource(projectModules) {
        return this.state.dataSource.cloneWithRows(projectModules);
    }

    updateState(dic) {
        if (!this) return;
        this.setState(dic);
    }

    onLoad(url) {
        this.setState({
            isLoading: true,
        });

        this.dataRespository
            .fetchRespository(url)
            .then(result => {
                this.items = result && result.items ? result.items : result ? result : [];
                // this.setState({
                //     result: JSON.stringify(items),
                //     dataSource: this.state.dataSource.cloneWithRows(items),
                //     isLoading: false,
                // });
                // this.flushFavoriteState(items);
                this.getFavoriteKey();
                if (result && result.update_date && !this.dataRespository.checkData(result.update_date)) {
                    DeviceEventEmitter.emit('showToast', '数据过时..');
                    //过时情况
                    return this.dataRespository.fetNetRespository(url);
                } else {
                    DeviceEventEmitter.emit('showToast', '加载缓存数据..');
                }
            })
            .then(items => {
                if (!items || items.length === 0) return;
                // this.setState({
                //     result: JSON.stringify(items),
                //     dataSource: this.state.dataSource.cloneWithRows(items),
                //     isLoading: false,
                // });
                // this.flushFavoriteState(items);
                this.getFavoriteKey();
                DeviceEventEmitter.emit('showToast', '加载网络数据..');
            })
            .catch(error => {
                this.updateState({
                    isLoading: false,
                });
            })
    }

    componentDidMount() {
        //页面装载之后调用
        this.onLoad(this.genUrl(this.state.searchTxt))
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.hTheme !== this.props.theme) {
            this.setState({
                theme: nextProps.hTheme
            })
        }
        this.flushFavoriteState();
    }

    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return <View key={rowID} style={styles.item_line}>
        </View>
    }

    goItemDetail(data) {
        this.props.navigator.push({
            component: RepositoryDetailPage,
            params: {
                projectModule: data,
                isTrending: false,
                ...this.props,//这个是延展属性，而延展属性中会有navigator
            },
        });
    }

    renderRow(projectModule) {
        return <RespositoryCell
            key={projectModule.item.id}
            goItemDetail={() => {
                this.goItemDetail(projectModule);
            }}
            projectModule={projectModule}
            onFavoritePressed={(item, isFavorite) => this.onFavoritePressed(item, isFavorite)}

            hTheme={this.state.theme}
            {...this.props}
        />
    }

    /** 这个是从二级组件回调的方法*/
    onFavoritePressed(item, isFavorite) {
        if (isFavorite)
            this.favoriteDao.savaFavoriteItem(item.id.toString(), JSON.stringify(item));
        else this.favoriteDao.removeFavoriteItem(item.id.toString())
    }

    onLoadRefresh() {
        setTimeout(() => {
            this.onLoad(this.genUrl(this.state.searchTxt));
        }, 1500);
    }

    render() {
        return <View style={{flex: 1}}>
            <ListView
                dataSource={this.state.dataSource}
                renderRow={(data) => this.renderRow(data)}
                renderSeparator={(sectionID, rowID, adjacentRowHighlighted) =>
                    this.renderSeparator(sectionID, rowID, adjacentRowHighlighted)}
                enableEmptySections={true}
                // renderFooter={() => this.renderFooter()}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onLoadRefresh()}
                    />}
            />

        </View>
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    boy_text: {
        fontSize: 18,
        color: 'black',
        alignSelf: 'center',
    },
    tab_image: {
        width: 20,
        height: 20,
    },
    text: {
        marginTop: 50,
        fontSize: 18,
        marginTop: 10,
        alignSelf: 'center',
    },
    button: {
        height: 60,
        marginTop: 30,
        fontSize: 20,
        alignSelf: 'center',
    },
    edt: {
        height: 50,
        marginTop: 30,
        minWidth: 300,
        alignSelf: 'center',
        borderColor: '#02F78E',
    },
    item_row: {
        height: 60
    }, item_line: {
        height: 1,
        backgroundColor: '#FCFCFC'
    },
});